package com.qf.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 根据请求参数中的apiname，查找对应的微服务和url路径
 * 并发送请求
 */
@Component
@Slf4j
public class DynamicRoutingFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        // 尊重之前过滤器的结果 ，如果之前的过滤器已经认为请求无需发送给微服务了，那么这个过滤器也不需要执行了
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean flag = currentContext.sendZuulResponse();
        log.info("DynamicRoutingFilter是否需要执行:{}", flag);
        return flag;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();
        String apiname = request.getParameter("apiname");

        String serviceName = findServiceName(apiname);
        String url = findServiceUrl(apiname);
        log.info("当前请求要发送给{}微服务的{}路径",serviceName,url);
        // 如何实现动态路由
        // 通过设置 FilterConstants.SERVICE_ID_KEY 可以影响请求要发送给哪个微服务
        currentContext.put(FilterConstants.SERVICE_ID_KEY,serviceName);
        // 通过设置FilterConstants.REQUEST_URI_KEY，可以影响请求要发送给微服务的哪个url路径
        currentContext.put(FilterConstants.REQUEST_URI_KEY,url);

        return null;
    }

    private String findServiceUrl(String apiname) {
        return "/user/get/1";
    }

    private String findServiceName(String apiname) {
        return "user";
    }
}
